package com.ruoyi.system.service.impl;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.dao.UploadDAO;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.sqlite.EngTable;
import com.ruoyi.system.domain.sqlite.FileInfo;
import com.ruoyi.system.domain.sqlite.VolumeInfo;
import com.ruoyi.system.mapper.*;
import org.apache.commons.compress.archivers.zip.ZipUtil;
import org.apache.commons.lang3.CharSetUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.ISysFileInfoService;
import org.springframework.web.multipart.MultipartFile;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;

import javax.sound.sampled.Mixer;
import java.nio.charset.Charset;

/**
 * 文件上传Service业务层处理
 *
 * @author GuangPipi
 * @date 2023-06-11
 */
@Service
public class SysFileInfoServiceImpl implements ISysFileInfoService {
    @Autowired
    private SysFileInfoMapper sysFileInfoMapper;
    @Autowired
    private ModuleEngInfoPreviewMapper moduleEngInfoPreviewMapper;
    @Autowired
    private ModuleVolumeInfoPreviewMapper moduleVolumeInfoPreviewMapper;
    @Autowired
    private ModuleVolumeInfoMapper moduleVolumeInfoMapper;
    @Autowired
    private ModuleFileInfoPreviewMapper moduleFileInfoPreviewMapper;
    @Autowired
    private ModuleEngSerialMapper moduleEngSerialMapper;
    @Autowired
    private ModuleTreemainMapper moduleTreemainMapper;
    @Autowired
    private ModuleFileInfoMapper moduleFileInfoMapper;

    /**
     * 查询文件上传
     *
     * @param engFileId 文件上传主键
     * @return 文件上传
     */
    @Override
    public SysFileInfo selectSysFileInfoByEngFileId(Long engFileId) {
        return sysFileInfoMapper.selectSysFileInfoByEngFileId(engFileId);
    }

    /**
     * 查询文件上传列表
     *
     * @return 文件上传集合
     */
    public List<SysFileInfo> getAllFileInfoList() {
        return sysFileInfoMapper.getAllFileInfoList();
    }

//    更改案卷名字
    public String changeName() {
        ModuleVolumeInfo moduleVolumeInfo = new ModuleVolumeInfo();
        List<ModuleVolumeInfo> moduleVolumeInfoList = moduleVolumeInfoMapper.selectModuleVolumeInfoList(moduleVolumeInfo);
        for(ModuleVolumeInfo moduleVolumeInfo1 : moduleVolumeInfoList) {
            ModuleFileInfo moduleFileInfo = new ModuleFileInfo();
            moduleFileInfo.setVolumeid(moduleVolumeInfo1.getId());
            List<ModuleFileInfo> moduleFileInfoList = moduleFileInfoMapper.selectModuleFileInfoList(moduleFileInfo);
            for(ModuleFileInfo moduleFileInfo1 : moduleFileInfoList) {
                if (moduleFileInfo1.getFilename().endsWith(".pdf")) {
                    // 使用正则表达式分割字符串，获取第一个空格前的数字
                    String[] parts = moduleFileInfo1.getFilename().split("\\s+", 2); // 2 表示最多分割一次
                    try {
                        int number = Integer.parseInt(parts[0]);
                        moduleVolumeInfo1.setVname("第"+String.valueOf(number)+"卷 "+moduleVolumeInfo1.getVname());
                    } catch (NumberFormatException e) {
                        continue;
                    }
                }
            }
            moduleVolumeInfoMapper.updateModuleVolumeInfo(moduleVolumeInfo1);
        }
        return "改命成功";
    }


    /**
     * 查询文件上传
     *
     * @param file 文件上传主键
     * @return 文件上传
     */
    public String importFilePath(MultipartFile file, Long engclass) {
        if (!file.isEmpty()) {
            try {
                // 存储地址设置
                Calendar calendar = Calendar.getInstance();
                String year = String.valueOf(calendar.get(Calendar.YEAR));
                String memoryAddress = "d:\\CJDA\\document\\" + year;
                File file1 = new File(memoryAddress);
                if (!file1.exists()) {
                    file1.mkdirs();
                }

                String fileName = file.getOriginalFilename();
                File dest = new File(memoryAddress + File.separator + fileName);
                String FileName = fileName;

                if (FileName.contains(".")) {
                    int index = FileName.indexOf(".");
                    FileName = FileName.substring(0, index);
                }

                file.transferTo(dest);
                // 创建文件所在
                String filePath = memoryAddress + File.separator + fileName;
                String FilePath = memoryAddress + File.separator + FileName;
                // 创建解压地址
                String destinationFolderPath = memoryAddress + File.separator;

                // 存储解压地址至本地
                boolean a = this.unzip(filePath, destinationFolderPath);
                // if (a){
                // String verify = this.Verify(FilePath);
                // if(verify.equals("true")){
                // SysFileInfo sysFileInfo = new SysFileInfo();
                // sysFileInfo.setFileName(FileName);
                // sysFileInfo.setFileDopath(FilePath);
                // sysFileInfo.setCreateTime(DateUtils.getNowDate());
                // sysFileInfoMapper.insertSysFileInfo(sysFileInfo);
                //// Long classno = getclass(FilePath);
                // this.insertData(FilePath,destinationFolderPath,engclass);
                // return "文件导入成功!";
                // }else {
                // File cfile = new File(filePath);
                // cfile.delete();
                // File directory = new File(FilePath);
                // this.delete(directory);
                // return verify;
                // }
                // } else {
                // return "文件导入失败!";
                // }
                if (a) {
                    SysFileInfo sysFileInfo = new SysFileInfo();
                    sysFileInfo.setFileName(FileName);
                    sysFileInfo.setFileDopath(FilePath);
                    sysFileInfo.setCreateTime(DateUtils.getNowDate());
                    sysFileInfoMapper.insertSysFileInfo(sysFileInfo);
                    this.insertData(FilePath, destinationFolderPath, engclass);
                    return "文件导入成功!";
                } else {
                    return "文件导入失败!";
                }
            } catch (IOException e) {
                e.printStackTrace();
                return "文件上传失败！";
            }
        } else {
            return "文件为空！";
        }
    }

    /**
     *
     * 删除文件夹
     *
     */
    public static void delete(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();

            if (files != null) {
                for (File subFile : files) {
                    delete(subFile);
                }
            }
        }
        file.delete();
    }

    // /**
    // *
    // *
    // * 获取类别编号
    // *
    // */
    // public Long getclass(String sqliteEngPath){
    // UploadDAO uploadDAO = new UploadDAO(sqliteEngPath);
    // List<EngTable> engTables = uploadDAO.getEng();
    // Long classno = 3L;
    // for (int i = 0; i < engTables.size(); i++){
    // EngTable engTable = engTables.get(i);
    // EngRegister engRegister = new EngRegister();
    // engRegister.setSecretKey(engTable.getEngNo());
    // List<EngRegister> engRegisterList =
    // engRegisterMapper.selectEngRegisterList(engRegister);
    // EngRegister engRegister1 = engRegisterList.get(0);
    // classno = Long.parseLong(engRegister1.getEngRegisterYuliu1());
    // }
    // return classno;
    // }

    /**
     *
     * 验证函数
     *
     */
    public String Verify(String sqliteEngPath) {
        UploadDAO uploadDAO = new UploadDAO(sqliteEngPath);
        List<EngTable> engTables = uploadDAO.getEng();
        for (int i = 0; i < engTables.size(); i++) {
            EngTable engTable = engTables.get(i);
            ModuleEngSerial moduleEngSerial = new ModuleEngSerial();
            moduleEngSerial.setEngNo(engTable.getEngNo());
            List<ModuleEngSerial> moduleEngSerialList = moduleEngSerialMapper
                    .selectModuleEngSerialList(moduleEngSerial);
            if (moduleEngSerialList.size() == 0) {
                return "工程识别号有误，请修正后再导入！";
            } else if (moduleEngSerialList.size() > 1) {
                return "工程识别号重复，请联系管理员！";
            } else {
                if (moduleEngSerialList.get(0).getCompleteFlag() == 1) {
                    return "工程识别码已经失效!";
                } else if (moduleEngSerialList.get(0).getCompleteFlag() == 0) {
                    if (moduleEngSerialList.get(0).getEngName().equals(engTable.getEngName())) {
                        return "true";
                    } else {
                        return "工程识别号与工程名称不符合，请修正后再导入！";
                    }
                } else if (moduleEngSerialList.get(0).getCompleteFlag() == 2) {
                    return "工程识别码已锁定，请于审核界面查看！";
                } else {
                    return "工程识别号状态有误，请查证！";
                }
            }
        }
        return "true";
    }

    /**
     *
     * 解压文件
     *
     */
    public boolean unzip(String zipFilePath, String destDir) {
        try {
            ZipFile zipFile = new ZipFile(zipFilePath);
            zipFile.setFileNameCharset(Charset.forName("GBK").toString());
            if (zipFile.isEncrypted()) {
                zipFile.setPassword("cjdapw");
            }
            zipFile.extractAll(destDir);
            return true;
        } catch (ZipException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 导入db文件于数据库
     */
    public void insertData(String sqliteEngPath, String destinationFolderPath, Long engclass) {
        UploadDAO uploadDAO = new UploadDAO(sqliteEngPath);

        List<EngTable> engTables = uploadDAO.getEng();
        List<String> stringList = this.transferEng(engTables, destinationFolderPath, engclass);
        String engPath = stringList.get(0);
        String engId = stringList.get(1);

        List<VolumeInfo> volumeInfos = uploadDAO.getVolume();
        HashMap<String, String> volumePaths = this.transferVolume(volumeInfos, engPath, engclass, engId);

        List<FileInfo> fileInfos = uploadDAO.getFile();
        this.transferFile(fileInfos, volumePaths);
    }

    /**
     * 导入工程信息于数据库
     */
    public List<String> transferEng(List<EngTable> engTables, String destinationFolderPath, Long engclass) {
        String engPath = destinationFolderPath;
        for (int i = 0; i < engTables.size(); i++) {
            EngTable engTable = engTables.get(i);
            ModuleEngInfoPreview moduleEngInfoPreview = new ModuleEngInfoPreview();

            // ModuleEngSerial moduleEngSerial = new ModuleEngSerial();
            // moduleEngSerial.setEngNo(engTable.getEngNo());
            // List<ModuleEngSerial> moduleEngSerialList =
            // moduleEngSerialMapper.selectModuleEngSerialList(moduleEngSerial);
            // ModuleEngSerial moduleEngSerial1 = moduleEngSerialList.get(0);

            // 在两个数据库的实体类之间转移数据
            moduleEngInfoPreview.setId(engTable.getId());
            moduleEngInfoPreview.setEngname(engTable.getEngName());
            moduleEngInfoPreview.setEngno(engTable.getEngNo()); // 工程识别号
            moduleEngInfoPreview.setDanganguanno(engTable.getDangAnGuanNo());
            moduleEngInfoPreview.setYijiaodanwei(engTable.getYiJiaoDanWei());
            moduleEngInfoPreview.setBianzhidatestart(engTable.getBianZhiDateStart());
            moduleEngInfoPreview.setBianzhidateend(engTable.getBianZhiDateEnd());
            moduleEngInfoPreview.setAllname(engTable.getEngAddress());
            moduleEngInfoPreview.setAnjuanshu(engTable.getAnJuanShu());
            moduleEngInfoPreview.setDanganguanname(engTable.getDangAnGuanName());
            moduleEngInfoPreview.setShuzihuadanwei(engTable.getShuZiHuaDanWei());
            moduleEngInfoPreview.setBuildingorg(engTable.getBuildingOrg());
            moduleEngInfoPreview.setOperationorg(engTable.getOperationOrg());
            moduleEngInfoPreview.setCheckorg(engTable.getCheckOrg());
            moduleEngInfoPreview.setDesignorg(engTable.getDesignOrg());
            moduleEngInfoPreview.setExplorationorg(engTable.getExplorationOrg());
            moduleEngInfoPreview.setSupervisionorg(engTable.getSupervisionOrg());
            moduleEngInfoPreview.setCheckIssueno(engTable.getCheckIssueNo());
            moduleEngInfoPreview.setPlanlicenseno(engTable.getPlanLicenseNo());
            moduleEngInfoPreview.setLandplanlicenseno(engTable.getLandPlanLicenseNo());
            moduleEngInfoPreview.setLandlicenseno(engTable.getLandLicenseNo());
            moduleEngInfoPreview.setOperationlicenseno(engTable.getOperationLicenseNo());
            moduleEngInfoPreview.setStartstation(engTable.getStartStation());
            moduleEngInfoPreview.setEndstation(engTable.getEndStation());
            moduleEngInfoPreview.setTotallength(engTable.getTotalLength());
            moduleEngInfoPreview.setProjmanager(engTable.getProjManager());

            moduleEngInfoPreview.setEngInfoYuliu2("咸阳区县");
            // moduleEngInfoPreview.setEngInfoYuliu1 (engclass);
            moduleEngInfoPreview.setEngInfoYuliu3(engPath + moduleEngInfoPreview.getEngname());
            ModuleTreemain moduleTreemain = new ModuleTreemain();
            moduleTreemain.setIndexId(engclass);
            List<ModuleTreemain> moduleTreemainlist = moduleTreemainMapper.selectModuleTreemainList(moduleTreemain);
            moduleEngInfoPreview.setEngInfoYuliu4(moduleTreemainlist.get(0).getId());
            moduleEngInfoPreviewMapper.insertModuleEngInfoPreview(moduleEngInfoPreview);
            engPath = engPath + moduleEngInfoPreview.getEngname();
            // ModuleEngSerial moduleEngSerial2 = new ModuleEngSerial();
            // moduleEngSerial2.setEngNo(engTable.getEngNo());
            // List<ModuleEngSerial> moduleEngSerialList1 =
            // moduleEngSerialMapper.selectModuleEngSerialList(moduleEngSerial2);
            // ModuleEngSerial moduleEngSerial3 =moduleEngSerialList1.get(0);
            // moduleEngSerial3.setCompleteFlag(2);
            // moduleEngSerialMapper.updateModuleEngSerial(moduleEngSerial3);
        }
        List<String> stringList = new ArrayList<String>();
        stringList.add(engPath);
        stringList.add(engTables.get(0).getId());
        return stringList;
    }

    /**
     * 导入案卷信息于数据库
     */
    public HashMap<String, String> transferVolume(List<VolumeInfo> volumeInfos, String engPath, Long engclass,
                                                  String engId) {
        String volumePath = engPath + File.separator;
        // 创建一个HashMap对象作为字典
        HashMap<String, String> volumePaths = new HashMap<>();
        Long maxPIndexId = 0L;
        Long maxIndexId = 0L;
        if (moduleVolumeInfoPreviewMapper.findMaxIndexId().size() > 0) {
            maxPIndexId = moduleVolumeInfoPreviewMapper.findMaxIndexId().get(0).getIndexId();
        }
        if (moduleVolumeInfoMapper.findMaxIndexId().size() > 0) {
            maxIndexId = moduleVolumeInfoMapper.findMaxIndexId().get(0).getIndexId();
        }
        Long realIndexId = Math.max(maxPIndexId, maxIndexId);
        // 遍历所有数据，并进行修改和转移
        for (int i = 0; i < volumeInfos.size(); i++) {
            VolumeInfo volumeInfo = volumeInfos.get(i);
            ModuleVolumeInfoPreview moduleVolumeInfoPreview = new ModuleVolumeInfoPreview();
            // 在两个数据库的实体类间转移数据
            moduleVolumeInfoPreview.setId(volumeInfo.getId()); // 所有属性一一对应
            moduleVolumeInfoPreview.setRegprojid(engId);
            moduleVolumeInfoPreview.setVname(volumeInfo.getVolumeName());
            String[] parts = volumeInfo.getVolumeName().split(" ");
            Long number = 0L;
            if (parts.length > 0) {
                number = Long.parseLong(parts[0]);
            }
            moduleVolumeInfoPreview.setListno(number);
            moduleVolumeInfoPreview.setCarrietype(volumeInfo.getCarrierType());
            moduleVolumeInfoPreview.setAmount(volumeInfo.getAmount());
            moduleVolumeInfoPreview.setSpec(volumeInfo.getSize());
            moduleVolumeInfoPreview.setBuildorganization(volumeInfo.getBuildOrganization());
            moduleVolumeInfoPreview.setSavetime(volumeInfo.getStoreType());
            moduleVolumeInfoPreview.setSecuritylayer(volumeInfo.getSecurityLayer());
            moduleVolumeInfoPreview.setFilestart(volumeInfo.getFileStart());
            moduleVolumeInfoPreview.setFileend(volumeInfo.getFileEnd());
            moduleVolumeInfoPreview.setInjectionperson(volumeInfo.getInjectionPerson());
            moduleVolumeInfoPreview.setCheckperson(volumeInfo.getCheckPerson());
            moduleVolumeInfoPreview.setInjectiondate(volumeInfo.getInjection());
            moduleVolumeInfoPreview.setCheckdate(volumeInfo.getCheckDate());
            moduleVolumeInfoPreview.setStoreposition(volumeInfo.getStorePosition());
            moduleVolumeInfoPreview.setAnnotations(volumeInfo.getComments());
            moduleVolumeInfoPreview.setPath(volumePath + volumeInfo.getVolumeName());
            ModuleTreemain moduleTreemain = new ModuleTreemain();
            moduleTreemain.setIndexId(engclass);
            List<ModuleTreemain> moduleTreemainlist = moduleTreemainMapper.selectModuleTreemainList(moduleTreemain);
            moduleVolumeInfoPreview.setTopnode(moduleTreemainlist.get(0).getId());
            moduleVolumeInfoPreview.setVolumeno(formatVolumeSerialNumber(engclass, number));
            moduleVolumeInfoPreview.setIndexId(realIndexId + number);
//            moduleVolumeInfoPreview.setVolumeYuliu3(String.valueOf(moduleVolumeInfoMapper.findMaxLuiShui() + 1));
            moduleVolumeInfoPreviewMapper.insertModuleVolumeInfoPreview(moduleVolumeInfoPreview);
            volumePaths.put(volumeInfo.getId(), volumePath + volumeInfo.getVolumeName() + File.separator);
        }
        return volumePaths;
    }



    public String formatVolumeSerialNumber(Long engclass, Long index) {
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String date = currentDate.format(formatter);
        ModuleTreemain moduleTreemain = new ModuleTreemain();
        moduleTreemain.setIndexId(engclass);
        List<ModuleTreemain> moduleTreemainlist = moduleTreemainMapper.selectModuleTreemainList(moduleTreemain);
        String classNo = "1";
        if (!moduleTreemainlist.isEmpty()) {
            String className = moduleTreemainlist.get(0).getIndexName();
            int spaceIndex = className.indexOf(" ");
            String beforeSpace = className.substring(0, spaceIndex);
            classNo = beforeSpace.replace(".", "");
        }
        return date + "-" + classNo + "-" + String.format("%07d", index);
    }

    /**
     * 导入文件信息于数据库
     */
    public void transferFile(List<FileInfo> fileInfos, HashMap<String, String> volumePaths) {
        // 遍历所有数据，并进行修改和转移
        for (int i = 0; i < fileInfos.size(); i++) {
            FileInfo fileInfo = fileInfos.get(i);
            ModuleFileInfoPreview moduleFileInfoPreview = new ModuleFileInfoPreview();
            // 在两个数据库的实体类间转移数据
            moduleFileInfoPreview.setId(fileInfo.getId()); // 所有属性一一对应
            moduleFileInfoPreview.setVolumeid(fileInfo.getVolumeId());
            moduleFileInfoPreview.setFilename(fileInfo.getFileName());
            moduleFileInfoPreview.setDuty(fileInfo.getDutyOrganization());
            moduleFileInfoPreview.setSavetime(fileInfo.getStoreType());
            moduleFileInfoPreview.setFiletime(fileInfo.getFileTime());
            moduleFileInfoPreview.setTagnum(fileInfo.getFileNo());
            moduleFileInfoPreview.setPagenumber(fileInfo.getPageNumber());
            moduleFileInfoPreview.setBuildorganization(fileInfo.getBuildOrganization());
            moduleFileInfoPreview.setCarriertype(fileInfo.getCarrierType());
            moduleFileInfoPreview.setPapertype(fileInfo.getPaperType());
            moduleFileInfoPreview.setSecuritylayer(fileInfo.getSecurityLayer()); // 所有属性一一对应
            moduleFileInfoPreview.setComments(fileInfo.getComments());
            moduleFileInfoPreview.setAbstracts(fileInfo.getAbstract());
            moduleFileInfoPreview.setKeywords(fileInfo.getKeyWords());
            String[] parts = fileInfo.getFileName().split(" ");
            if (parts.length > 0) {
                Long number = Long.parseLong(parts[0]);
                moduleFileInfoPreview.setEfilenum(number);
            }
            // 插入文件类型
            String folderPath = volumePaths.get(fileInfo.getVolumeId());
            String houzhui = "jpg";
            File folder = new File(folderPath);
            if (folder.isDirectory()) {
                Map<String, String> fileDetails = new HashMap<>();
                readFiles(folder, fileDetails);
                moduleFileInfoPreview.setFileReserved1(fileDetails.get(fileInfo.getFileName()));
                houzhui = fileDetails.get(fileInfo.getFileName());
            }
            moduleFileInfoPreview
                    .setFilepath(volumePaths.get(fileInfo.getVolumeId()) + fileInfo.getFileName() + "." + houzhui);
            moduleFileInfoPreviewMapper.insertModuleFileInfoPreview(moduleFileInfoPreview);
        }
    }

    // 读取文件名称与类型
    public static void readFiles(File folder, Map<String, String> fileDetails) {
        File[] files = folder.listFiles(); // 获取文件夹中的所有文件

        for (File file : files) {
            if (file.isDirectory()) {
                readFiles(file, fileDetails); // 递归遍历子文件夹中的文件
            } else {
                String fileName = file.getName();
                String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
                String nameWithoutExtension = fileName.substring(0, fileName.lastIndexOf("."));
                fileDetails.put(nameWithoutExtension, fileType); // 将不带类型的文件名称和类型存储到字典中
            }
        }
    }

    /**
     * 查询文件上传列表
     *
     * @param sysFileInfo 文件上传
     * @return 文件上传
     */
    @Override
    public List<SysFileInfo> selectSysFileInfoList(SysFileInfo sysFileInfo) {
        return sysFileInfoMapper.selectSysFileInfoList(sysFileInfo);
    }

    /**
     * 新增文件上传
     *
     * @param sysFileInfo 文件上传
     * @return 结果
     */
    @Override
    public int insertSysFileInfo(SysFileInfo sysFileInfo) {
        return sysFileInfoMapper.insertSysFileInfo(sysFileInfo);
    }

    /**
     * 修改文件上传
     *
     * @param sysFileInfo 文件上传
     * @return 结果
     */
    @Override
    public int updateSysFileInfo(SysFileInfo sysFileInfo) {
        return sysFileInfoMapper.updateSysFileInfo(sysFileInfo);
    }

    /**
     * 批量删除文件上传
     *
     * @param engFileIds 需要删除的文件上传主键
     * @return 结果
     */
    @Override
    public int deleteSysFileInfoByEngFileIds(Long[] engFileIds) {
        return sysFileInfoMapper.deleteSysFileInfoByEngFileIds(engFileIds);
    }

    /**
     * 删除文件上传信息
     *
     * @param engFileId 文件上传主键
     * @return 结果
     */
    @Override
    public int deleteSysFileInfoByEngFileId(Long engFileId) {
        return sysFileInfoMapper.deleteSysFileInfoByEngFileId(engFileId);
    }
}
